<template>
  <view class="deco-vip-buy-button" :style="[innerStyle]">
    <zm-footer v-if="!readOnly">
      <view v-if="from.type == 'vipOne'">
        <view v-if="!login" class="button-content" @click="handleAuthLogin">登录免费领取</view>
      </view>
      <view v-if="from.type == 'vipTwo'" class="relative">
        <view v-if="(vipLevel != 2 || !login) && showOriginalPrice" class="vip-origina-price">原价{{ currentRule.rule.originalPrice | formatDigit }}</view>
        <view v-if="vipLevel != 2 || !login" class="button-content" @click="handleBuy">{{ currentRule.rule.buyButtonTitle }}</view>
      </view>
    </zm-footer>

    <!-- 支付弹框 -->
    <pay-way-popup ref="pay" max-height="70vh">
      <view slot="payHeader" class="flex flex-col px-24">
        <text class="font-32 font-bold py-30 px-6 theme-text">限时促销优惠</text>
        <view class="grid grid-cols-3 radius-16 bg-white px-24 py-30 gap-x-22">
          <view v-for="(item, index) in rules" :key="index" class="rule-item" :class="{ 'is-active': item.id === ruleId }" @click="handleClickRule(item)">
            <image v-if="item.id === ruleId" class="vip-rule-bg" :src="useImage('/zuimei-film-oss/1.0.0/images/vip-rule-bg.png')" mode="scaleToFill" />
            <view v-if="item.rule.label" class="vip-rule-label">{{ item.rule.label }}</view>
            <text class="font-28 font-bold relative z-10" :style="{ color: item.id === ruleId ? '#7b2e06' : '#333' }">{{ item.rule.ruleName }}</text>
            <text class="discount-price relative z-10" :style="{ color: item.id === ruleId ? '#7b2e06' : '#333' }">{{ item.rule.discountPrice | formatDigit }}</text>
            <text
              v-if="Number(item.rule.originalPrice) > Number(item.rule.discountPrice)"
              class="font-28 font-500 text-line-through relative z-10"
              :style="{ color: item.id === ruleId ? '#AF8169' : '#333' }"
            >
              ¥{{ item.rule.originalPrice | formatDigit }}
            </text>
          </view>
        </view>
      </view>

      <view slot="payFooter" class="footer-wrap" :style="{ 'margin-bottom': tabbarHeight + 10 + 'px' }">
        <view class="button-content" @click="handlePay">
          <text>{{ currentRule.rule.buyButtonTitle }}</text>
          <text v-if="Number(currentRule.rule.originalPrice) > Number(currentRule.rule.discountPrice)" class="vip-origina-price">原价{{ currentRule.rule.originalPrice | formatDigit }}</text>
        </view>

        <view class="flex justify-center">
          <zm-checkbox v-model="isAgreest" icon-size="28rpx" round icon-color="#7B2E06" checked-icon-color="#7B2E06">
            <view class="checkbox-text">
              <text class="text-999">开通会员代表接受</text>
              <text :style="{ color: '#7B2E06' }" @click.stop="handleToUserAt">《会员服务协议》</text>
            </view>
          </zm-checkbox>
        </view>
      </view>
    </pay-way-popup>
    <!-- 会员开通弹窗 -->
    <deco-vip-popup ref="popup" :data="from"></deco-vip-popup>
  </view>
</template>

<script>
import mixin from "@/decoration/mixins"
import { mapGetters } from "vuex"
export default {
  name: "deco-vip-buy-button",
  mixins: [mixin],
  data() {
    return {
      rules: [],
      ruleId: "",
      readOnly: false,
      vipCardInfo: {},
      isAgreest: false,
      tabbarHeight: 0
    }
  },
  computed: {
    ...mapGetters(["login", "userInfo"]),
    themeColorRgba() {
      return (a = 1) => {
        const { r, g, b } = uni.$hexToRgb(this.from?.config?.themeColor || "#6F0282")
        return `rgba(${r},${g},${b}, ${a})`
      }
    },
    currentRule() {
      return this.rules.find((item) => item.id === this.ruleId) || { rule: {} }
    },
    showOriginalPrice() {
      return Number(this.currentRule?.rule?.originalPrice ?? 0) > Number(this.currentRule?.rule?.discountPrice ?? 0)
    },
    vipLevel() {
      return this.userInfo.level
    }
  },
  created() {},
  mounted() {
    this.readOnly = this.decoEntryCommon.readOnly
    this.tabbarHeight = this.decoEntryCommon.isTabbar ? 70 : 0
    this.onEvents()
    this.handleGetOpenCardRule()
  },
  methods: {
    onEvents() {
      this.mitt.on("deco-vip-buy-button.open", (type) => {
        if (type === this.from?.type) {
          this.$refs.pay.show({ orderType: "equityCard" })
        }
      })
    },
    handleClickRule(rule) {
      this.ruleId = rule.id
    },
    handleAuthLogin() {
      uni.$emit(`${this.useCurrentRoute()}-login`)
    },
    handleBuy() {
      if (this.login) {
        this.$refs.pay.show({ orderType: "equityCard" })
      } else {
        uni.$emit(`${this.useCurrentRoute()}-login`)
      }
    },
    async handlePay() {
      // 会员卡创建订单 会员等级不是普通会员的话就是续卡,1开发2续卡
      if (this.isAgreest) {
        const way = this.userInfo.level == "1" ? "1" : "2"
        const res = await uni.$api.vipCardV2.createVipCardOrder({ way, ruleId: this.ruleId })
        if (res.filmOrderId) {
          uni
            .$confirm({
              title: "您有一笔待支付的会员订单，请前往影票订单中支付",
              cancelText: "取消订单",
              confirmText: "去支付"
            })
            .then(() => {
              this.toView({
                url: "pages/order/order-film-info/order-film-info",
                params: {
                  orderId: res.filmOrderId
                }
              })
            })
            .catch(() => {
              uni.$api.orderFilm.unLockSeat({ orderId: res.filmOrderId }).then(() => {
                uni.$toast("订单取消成功")
              })
            })
        } else {
          // 唤起支付
          if (uni.$uniPlatform === "web") {
            this.$refs.pay.webCreateOrderPay(
              { payMoney: res.payPrice, orderId: res.orderId, orderType: "equityCard" },
              {
                success: () => {
                  uni.navigateBack({ delta: 1 })
                  this.$refs.popup.show({ type: way })
                }
              }
            )
          } else {
            this.$refs.pay.createOrderPay({
              orderId: res.orderId,
              payMoney: res.payPrice,
              success: () => {
                uni.navigateBack({ delta: 1 })
                this.$refs.popup.show({ type: way })
              }
            })
          }
        }
      } else {
        this.$toast("请先勾选会员开通服务协议")
      }
    },
    async handleGetOpenCardRule() {
      // 调用接口获取开卡规则
      const res = await uni.$api.vipCardV2.getOpenCardRule()
      // 判断接口返回是否有规则列表
      if (res?.ruleList) {
        // 将规则列表赋值给rules
        this.rules = res.ruleList
        // 将规则列表第一个id赋值给ruleId
        this.ruleId = res.ruleList[0].id
      }
      this.vipCardInfo = res.vipCardInfo
    },
    handleToUserAt() {
      this.$setCache("richtext", {
        title: "《会员服务协议》",
        content: this.vipCardInfo.agreement
      })
      uni.$toView("pages/utils/richtext/richtext")
    }
  }
}
</script>

<style lang="scss" scoped>
.text-color {
  color: #7b2e06;
}
.footer-wrap {
  padding: 0 24rpx;
  .button-content {
    margin-top: 15rpx;
    margin-bottom: 24rpx;
    margin-left: 0;
    margin-right: 0;
  }
}
.theme-text {
  color: #572e00;
}

.vip-origina-price {
  position: absolute;
  top: -30rpx;
  right: 150rpx;
  z-index: 101;
  height: 44rpx;
  padding: 0 20rpx;
  color: #fff;
  display: flex;
  align-items: center;
  background: linear-gradient(90deg, #ff482a 0%, #ff9059 100%);
  border-radius: 22rpx;
  font-size: 24rpx;
  &::before {
    content: "";
    position: absolute;
    border-color: #ff5d37 transparent transparent transparent;
    border-style: solid;
    width: 0;
    height: 0;
    border-width: 14rpx;
    top: 0;
    left: 0;
    margin-top: 40rpx;
    margin-left: 30rpx;
  }
}
.button-content {
  height: 100rpx;
  color: #572e00;
  position: relative;
  display: flex;
  margin: 0 24rpx;
  font-size: 32rpx;
  font-weight: bold;
  align-items: center;
  margin-top: 35rpx;
  margin-bottom: 24rpx;
  border-radius: 50rpx;
  justify-content: center;
  background: linear-gradient(113deg, #faddaf 0%, #febc7e 100%);
  .button-discount-price {
    font-size: 48rpx;
    font-weight: bold;
    position: relative;
    &::before {
      content: "¥";
      font-size: 30rpx;
      font-weight: bold;
    }
  }
}

.buy-popup {
  left: 0;
  right: 0;
  bottom: 0;
  position: fixed;
}
.rule-item {
  flex: 1;
  height: 245rpx;
  display: flex;
  position: relative;
  align-items: center;
  border-radius: 16rpx;
  flex-direction: column;
  justify-content: center;
  background-color: #fffbf2;
  border: 2rpx solid #fffbf2;
  overflow: hidden;
  &.is-active {
    border-color: #eaa85e;
  }
  .vip-rule-bg {
    top: 0;
    left: 0;
    width: calc(100% + 3rpx);
    height: 100%;
    position: absolute;
  }
  .vip-rule-label {
    position: absolute;
    left: -1rpx;
    top: -1rpx;
    background: linear-gradient(90deg, #ff482a 0%, #ffaa6c 100%);
    border-radius: 16rpx 0rpx 16rpx 0rpx;
    color: #fff;
    font-size: 20rpx;
    padding: 0 12rpx;
    height: 32rpx;
    min-width: 106rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .discount-price {
    font-size: 56rpx;
    font-weight: bold;
    position: relative;
    &::before {
      content: "¥";
      font-size: 32rpx;
      font-weight: bold;
    }
  }
}
</style>
